package com.jiunuan.live.im.provider.service.impl;

import com.jiunuan.live.framework.redis.starter.key.IMProviderCacheKeyBuilder;
import com.jiunuan.live.im.provider.service.ImTokenService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: JiuNuan
 * @CreateTime: 2024-08-13 13:51
 * @Description: token校验实现
 */
@Service
public class ImTokenServiceImpl implements ImTokenService {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private IMProviderCacheKeyBuilder cacheKeyBuilder;
    /**
     * 创建用户登录im服务的token
     *
     * @param userId
     * @param appId
     * @return
     */
    @Override
    public String createImLoginToken(long userId, int appId) {
        String token = UUID.randomUUID() + "%" + appId;
        redisTemplate.opsForValue().set(cacheKeyBuilder.buildIMLoginToken(token),userId,5, TimeUnit.MINUTES);
        return token;
    }

    /**
     * 根据token检索用户id
     *
     * @param token
     * @return
     */
    @Override
    public Long getUserIdByToken(String token) {
        Object userId = redisTemplate.opsForValue().get(cacheKeyBuilder.buildIMLoginToken(token));
        if(userId == null){
            return null;
        }
        return Long.valueOf(userId.toString());
    }
}
